"""
协作管理相关的数据模型
"""
from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional
from datetime import datetime
from enum import Enum


class ConflictType(Enum):
    """冲突类型枚举"""
    CONTENT_CONFLICT = "content_conflict"
    STRUCTURE_CONFLICT = "structure_conflict"
    PERMISSION_CONFLICT = "permission_conflict"


class ChangeType(Enum):
    """变更类型枚举"""
    INSERT = "insert"
    DELETE = "delete"
    UPDATE = "update"
    MOVE = "move"


class EditingStatus(Enum):
    """编辑状态枚举"""
    ACTIVE = "active"
    IDLE = "idle"
    DISCONNECTED = "disconnected"


@dataclass
class Change:
    """表示文档变更的数据模型"""
    id: str
    user_id: str
    timestamp: datetime
    change_type: ChangeType
    position: int
    content: str
    length: int = 0
    metadata: Dict[str, Any] = field(default_factory=dict)


@dataclass
class Conflict:
    """表示编辑冲突的数据模型"""
    id: str
    conflict_type: ConflictType
    users_involved: List[str]
    changes: List[Change]
    description: str
    timestamp: datetime
    resolved: bool = False
    resolution_strategy: Optional[str] = None


@dataclass
class Resolution:
    """表示冲突解决方案的数据模型"""
    conflict_id: str
    strategy: str
    resolved_content: str
    resolver_user_id: str
    timestamp: datetime
    accepted_changes: List[str]
    rejected_changes: List[str]


@dataclass
class EditingSession:
    """表示编辑会话的数据模型"""
    session_id: str
    project_id: str
    user_id: str
    start_time: datetime
    last_activity: datetime
    status: EditingStatus
    cursor_position: int = 0
    selected_range: Optional[tuple] = None
    permissions: List[str] = field(default_factory=list)


@dataclass
class Version:
    """表示文档版本的数据模型"""
    version_id: str
    project_id: str
    version_number: int
    timestamp: datetime
    author_id: str
    changes: List[Change]
    commit_message: str
    parent_version_id: Optional[str] = None
    content_hash: str = ""


@dataclass
class ActivityLog:
    """表示活动日志的数据模型"""
    project_id: str
    activities: List[Dict[str, Any]]
    start_date: datetime
    end_date: datetime
    total_activities: int
    
    def add_activity(self, user_id: str, action: str, details: Dict[str, Any]):
        """添加活动记录"""
        activity = {
            "timestamp": datetime.now(),
            "user_id": user_id,
            "action": action,
            "details": details
        }
        self.activities.append(activity)
        self.total_activities += 1


@dataclass
class CollaborationState:
    """表示协作状态的数据模型"""
    project_id: str
    active_sessions: List[EditingSession]
    pending_conflicts: List[Conflict]
    recent_changes: List[Change]
    current_version: Version
    last_sync_time: datetime